import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../generated/l10n.dart';

void main() {
  runApp(LocaleTest());
}

class LocaleTest extends StatefulWidget {
  const LocaleTest({super.key});

  @override
  State<LocaleTest> createState() => _LocaleTestState();
}

class _LocaleTestState extends State<LocaleTest> {
  Locale _locale = Locale('zh', 'CN'); // 初始Locale

  void _changeLocale(Locale locale) {
    setState(() {
      _locale = locale;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate, // 以MaterialApp为入口的应用
        // GlobalWidgetsLocalizations.delegate, // 以WidgetApp为入口的应用
        // 注册我们的Delegate
        S.delegate,
      ],
      locale: _locale,
      supportedLocales: S.delegate.supportedLocales,
      home: HomeDemo(_changeLocale),
      // 不行，context还没构建完呢
      // title: S.of(context).app_title,
      onGenerateTitle: (context) => S.of(context).app_title,
    );
  }
}

class HomeDemo extends StatelessWidget {
  HomeDemo(this.changeLocale);

  final ValueChanged<Locale> changeLocale;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(S.of(context).app_title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(S.of(context).hello("sbjun")),
            SizedBox(height: 30),
            Text("Intl插件，省去了自己写LocalizationDelegate代码"),
            Text("自动生成arb 和 Delegate文件和结构，但是key值变了，Delegate.dart就会变化"),
            Text("作者这节将的不好，不如直接"),
            GestureDetector(
              onTap: () async {
                await launchUrlString(
                    "https://plugins.jetbrains.com/plugin/13666-flutter-intl");
              },
              child: Text('Flutter_intl官网',
                  style: TextStyle(
                      color: Colors.blue,
                      decoration: TextDecoration.underline)),
            ),
          ],
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.miniEndTop,
      floatingActionButton: ElevatedButton.icon(
        icon: Icon(Icons.switch_access_shortcut),
        onPressed: () {
          // Locale locale = Localizations.localeOf(context);
          String locale = Intl.getCurrentLocale();
          if (locale == 'zh') {
            changeLocale(const Locale('en', 'US'));
          } else {
            changeLocale(const Locale('zh', 'CN'));
          }
        },
        label: Text(S.of(context).button_label), // 你可以更换为你需要的图标
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
